import React, { useState, useEffect } from 'react';
import { Modal, Button, Skeleton, Image, message, Upload, Row, Col, Space, AutoComplete,Typography, Checkbox, Input } from 'antd'
import { UploadOutlined, LoadingOutlined, PlusOutlined, SearchOutlined } from '@ant-design/icons';
import {
  ProFormText,
  ProForm,
  ProFormDatePicker,
  ProFormDateTimePicker,
  ProFormSelect,
  ProFormTextArea,
  ProFormUploadButton,
  ProFormCascader,
  ProFormRadio,
  CheckCard
} from '@ant-design/pro-components';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import { information } from '@/utils/rules';
import Utils from 'fr-util/utils';
import type { EditModalProps } from '../data';

import CameraModal from '@/components/CameraModal'
import Search from '@/components/Search'

import cityList from '@/utils/city'
import { apply } from '@/utils/rules'

import {
  addCreatePatient,
  addUpdatePatient,
  getPatientDetail,
  getOrganizeCreate,
  getOrganizeUpdate,
  reqRecommendList,
  getOrganizeList,
  reqGroupList,
  fileUpload
} from '@/services/register';

import styles from './index.module.less'
import { reqTyOrganizeList } from '@/services/tyorganize';

const EditModal: React.FC<EditModalProps> = ({ row, isOpen, activeKey, handleModal, actionRef }) => {
  const title = row?.id ? "修改" : "添加患者信息"
  const [formObj] = ProForm.useForm()
  const [initialValues, setinitialValues] = useState<any>(null)
  const [cardpicture, setCardpicture] = useState(null)
  const [avatar, setAvatar] = useState(null)
  // 创建
  const handleAdd = async (params: any) => {

    let reqData = { cardpicture, avatar, ...params };
    if (Array.isArray(reqData?.province) && reqData?.province?.length > 0) {
      reqData.city = reqData.province[0];
      reqData.region = reqData.province[1];
      reqData.province = reqData.province[2];
    }
    const res = await addCreatePatient(reqData)
    if (res?.resultCode === "00000000") {
      message.success(res?.message)
      actionRef?.current.reload()
      handleModal(false)
    } else {
      message.error(res?.message)
    }
  }

  // 修改
  const handleEditor = async (params: any) => {
    const res = await addUpdatePatient({ type: activeKey, ...params, id: row?.id })
    if (res.code == 200) {
      message.success(res?.message)
      actionRef?.current.reload()
      handleModal(false)
    } else {
      message.error(res?.message)
    }
  }

  useEffect(() => {
    if (row?.id) {
      let { id, phoneNumber, answerData, actId } = row

      setinitialValues({
        id, phoneNumber, answerData, actId
      })
    }

    //handleActIdData({});
  }, [])

  console.log('cityList :>> ', cityList);


  async function getRecommendList() {
    const res = await reqRecommendList({pageSize:100});
    const mapArr = res.data.map((item: any) => ({
      value: item?.id,
      label: item?.realName,
    }))
    return mapArr;
  }

  async function getGroupList() {
    const res = await reqGroupList({});
    const mapArr = res?.data?.result?.map((item: any) => ({
      value: item?.id,
      label: item?.groupName,
    }))
    return mapArr;
  }


  async function getOrganizeListApi() {
    const res = await getOrganizeList({current:1,pageNum:1,pageSize:100});
    const mapArr = res?.data?.result?.map((item: any) => ({
      value: item?.id,
      label: item?.name,
    }))
    console.log('getOrganizeListApi :>> ', mapArr);
    return mapArr;
  }

  //将base64转换为blob
  function dataURLtoBlob(dataurl) {
    var arr = dataurl.split(','),
      mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]),
      n = bstr.length,
      u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
  }

  //将blob转换为file
  function blobToFile(theBlob, fileName) {
    theBlob.lastModifiedDate = new Date();
    theBlob.name = fileName;
    return theBlob;
  }


  async function onChangeImage(imgUrl: any) {
    // const img = '';

    //调用
    // let blob = dataURLtoBlob(base64Data);
    // let file = blobToFile(blob, '');
    // // console.log('file :>> ', file, base64Data);
    // const formData = new FormData();
    // formData.append("file", file);
    // const res = await fileUpload(formData);

    // console.log('res :>> ', res.data);
    setCardpicture(imgUrl)

  }


  const [dataList,setDataList] = useState();
  const [checkValue,setCheckValue] = useState<string>();

  const handleSearch = async (value: string) => {
    let params = {pageSize:20};
    Object.assign(params,{"keyword":value});
    const res = await reqTyOrganizeList(params);
    if(res?.resultCode == "00000000"){
      setDataList(res?.data?.result);
    }
  };
  const onChangeCheckCard = (item: string) =>{
    formObj.setFieldValue("tyOrganizeId",item?.id);
    formObj.setFieldValue("tyOrganizeName",item?.name);
    setOpen(false)
  }

  const onSearch = (searchText: string) => {
      // setOptions(
      // !searchText ? [] : dataList
      // );
  };

  const onSelect = (data: string) => {
      console.log('onSelect', data);
  };

  async function onChangeAvatarImage(imgUrl: any) {
    setAvatar(imgUrl)
  }

  function onDataItems(key:any){
    let datatpm = ["111","222","333"];
    setDataList(datatpm);
  }
  const [open, setOpen] = useState<boolean>(false);

  const search = ()=>{
      setOpen(true);
  }

  return (
    <Modal
      width={800} title={title}
      open={isOpen}
      onCancel={() => handleModal(false)}
      footer={null}
      destroyOnClose={true}
    >
      {
        initialValues === null && row?.id ? <Skeleton active paragraph={{ rows: 6 }} /> :
          <ProForm
            form={formObj}
            initialValues={initialValues}
            onFinish={(values): Promise<any> => row?.id ? handleEditor(values) : handleAdd(values)}>
            <Row gutter={24}>
              <Col span={0}><ProFormText name="tyOrganizeId" hidden /></Col>
              <Col span={8}>
                {/* <ProFormText name="ty_organize_id" label="选择团体账号" placeholder="请选择团体账号" disabled /> */}
                 {/* <ProFormSelect
                  request={getOrganizeListApi}
                  options={[
                    {
                      value: '0',
                      label: '团体账号1',
                    },
                    {
                      value: '1',
                      label: '团体账号2',
                    },
                  ]}
                  name="tyOrganizeId"
                  label="请选择团体账号"
                /> */}
                <div onClick={search}>
                    <ProFormText name="tyOrganizeName" label="选择团体账号" placeholder="请选择团体账号" style={{"position":"relative"}} />
                    {/* <SearchOutlined style={{"position":"absolute","right":26,"top":36,"fontSize":20}}/> */}
                </div>
                {
                  open ?  
                  <Modal title="搜索" onCancel={()=>setOpen(false)} open={open} footer={[
                      <Button key="back" onClick={()=>setOpen(false)}>
                        关闭
                      </Button>]}>
                      <AutoComplete
                          dropdownMatchSelectWidth={252}
                          style={{ width: '100%' }}
                          options={[]}
                          onSelect={onSelect}
                          onSearch={handleSearch}
                          autoFocus={true}
                          >
                      </AutoComplete>
                      <CheckCard.Group
                          onChange={onChangeCheckCard}
                          style={{marginTop:10}}
                        >
                          {
                            dataList?.map((item, index) => {
                              return (
                                  <CheckCard
                                        key={index}
                                        title={item?.name}
                                        value={item}
                                        style={{width:'120px',textAlign:'center'}}
                                      />
                              )
                            })
                          }
                        </CheckCard.Group>

                  </Modal>: null
                }
              </Col>
              <Col span={0}>
                <ProFormText name="ty_organize_name" label="团队账号名称" placeholder="请输入团队账号名称" disabled />
              </Col>
              <Col span={8}>
                <ProFormText
                  name="phoneNum"
                  label="手机号"
                  placeholder="请输入手机号"
                  fieldProps={{
                    showCount: true,
                    maxLength: 11,
                  }}
                  rules={apply?.contactPhone}
                />
              </Col>
              {/* <Col span={12}>
                <ProFormSelect
                  request={getGroupList}
                  options={[
                    {
                      value: '0',
                      label: '分组1',
                    },
                    {
                      value: '1',
                      label: '分组2',
                    },
                  ]}
                  name="tyGroupName"
                  label="请选择分组"
                />
              </Col> */}
              <Col span={8}>
                <ProFormText name="name" label="姓名" placeholder="请输入姓名" />
              </Col>
              <Col span={8}>
                <ProFormText name="remark" label="备注名" placeholder="请输入备注名" />
              </Col>
              <Col span={8}>
                <ProFormSelect
                  options={[
                    {
                      value: '0',
                      label: '男',
                    },
                    {
                      value: '1',
                      label: '女',
                    },
                  ]}
                  name="gender"
                  label="性别"
                />
              </Col>
              <Col span={8}>
                <ProFormDatePicker
                  name="birthday"
                  label="生日"
                  fieldProps={{
                    format: "YYYY-MM-DD"
                  }}
                  placeholder="请输入生日"
                />
              </Col>
              <Col span={8}>
                <ProFormText name="height" label="身高" placeholder="请输入身高" />
              </Col>
              <Col span={8}>
                <ProFormText name="weight" label="体重" placeholder="请输入体重" />
              </Col>
              <Col span={8}>
                <ProFormText
                  name="email"
                  label="邮箱"
                  placeholder="请输入邮箱地址"
                />
              </Col>
              <Col span={8}>
                <ProFormCascader
                  name="province"
                  fieldProps={{
                    options: cityList,
                  }}
                  label="省/市/区"
                />
                {/* <ProFormText name="province" label='省/市/区' placeholder="请输入省/市/区" /> */}
              </Col>
              <Col span={24}>
                <ProFormText name="address" label="" placeholder="请输入详细地址" />
              </Col>
              <Col span={12}>
                <ProFormText
                  name="cardID"
                  label="证件号码"
                  fieldProps={{
                    showCount: true,
                    maxLength: 18,
                  }}
                  placeholder="请输入证件号码"
                  rules={apply?.idNo}
                />
              </Col>
              <Col span={8}>
                <ProFormSelect
                  request={getRecommendList}
                  name="recommendName"
                  label="请输入推荐人"
                />
              </Col>
              <Col span={8}>
                {/* <ProFormText name="recommend_name" label="推荐人" placeholder="请输入推荐人" /> */}
                <ProFormRadio.Group
                  name="receiveMethod"
                  // layout="vertical"
                  label="默认取药方式"
                  fieldProps={{
                    defaultValue: '1'
                  }}
                  options={[
                    {
                      label: '自取',
                      value: '1',
                    },
                    {
                      label: '邮寄',
                      value: '2',
                    },
                  ]}
                />
              </Col>
              <Col span={12}>
                <Space className={styles.space} size={25}>
                  <Space direction="vertical" size={20}>
                    <CameraModal onChangeImage={onChangeImage} />
                    {cardpicture && <img src={`${cardpicture}`} alt='' style={{ width: 100, height: 50 }} />}
                  </Space>
                  <Space direction="vertical" size={20}>
                    <CameraModal onChangeImage={onChangeAvatarImage} btnName='用户头像' />
                    {avatar && <img src={`${avatar}`} alt='' style={{ width: 80, height: 80 }} />}
                  </Space>
                </Space>
              </Col>
            </Row>
          </ProForm>
      }
    </Modal >
  );
};
export { EditModal }

